﻿using DevExpress.XtraEditors;
using MesProjectWinform.Public;
using MesProjectWinform.Public.Common;
using MesProjectWinform.WareHouse.Entity;
using MesProjectWinform.用户控件;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.WareHouse.Form.来料标签打印
{
    public partial class Form_ShowPrintcs : DevExpress.XtraEditors.XtraForm
    {
        // 分页相关变量
        private PaginationControl paginationControl;
        private int currentPage = 1;
        private int pageSize = 10;
        private int totalCount = 0;

        public Form_ShowPrintcs()
        {
            InitializeComponent();
            InitializePaginationControl();
        }

        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitializePaginationControl()
        {
            paginationControl = new PaginationControl();
            paginationControl.Dock = DockStyle.Bottom;
            paginationControl.PageChanged += PaginationControl_PageChanged;
            this.Controls.Add(paginationControl);
            paginationControl.BringToFront();
        }

        /// <summary>
        /// 分页控件页码变更事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PaginationControl_PageChanged(object sender, EventArgs e)
        {
            currentPage = paginationControl.CurrentPage;
            pageSize = paginationControl.PageSize;
            LoadData();
        }

        /// <summary>
        /// 查询  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnQry_Click(object sender, EventArgs e)
        {
            currentPage = 1; // 重置为第一页
            if (paginationControl != null)
            {
                paginationControl.CurrentPage = currentPage;
            }
            LoadData();
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClear_Click(object sender, EventArgs e)
        {
            TxtCode.Text = string.Empty;
            TxtName.Text = string.Empty;
            currentPage = 1;
            if (paginationControl != null)
            {
                paginationControl.CurrentPage = currentPage;
            }
            LoadData();
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnExport_Click(object sender, EventArgs e)
        {
            try
            {
                if (gridControl1.DataSource == null || gridView1.RowCount == 0)
                {
                    MessageBox.Show("没有可导出的数据！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Excel 文件|*.xlsx";
                saveFileDialog.Title = "导出数据";
                saveFileDialog.DefaultExt = "xlsx";
                saveFileDialog.FileName = "标签打印记录_" + DateTime.Now.ToString("yyyyMMddHHmmss");

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    Cursor = Cursors.WaitCursor;
                    gridControl1.ExportToXlsx(saveFileDialog.FileName);
                    Cursor = Cursors.Default;

                    if (MessageBox.Show("导出成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveFileDialog.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出过程中发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        
        private void Form_ShowPrintcs_Load(object sender, EventArgs e)
        {
            LoadData(); // 加载初始数据
        }

        #region 自定义方法
        /// <summary>
        /// 加载数据
        /// </summary>
        private async void LoadData()
        {
            try
            {
                // 禁用分页控件，防止重复操作
                if (paginationControl != null)
                {
                    paginationControl.Enabled = false;
                }

                // 显示等待光标
                Cursor = Cursors.WaitCursor;

                string action;

                // 对查询参数进行URL编码，避免特殊字符问题
                string encodedCode = Uri.EscapeDataString(TxtCode.Text.Trim());
                string encodedName = Uri.EscapeDataString(TxtName.Text.Trim());
                action = $"WareHouse/LablePrint/GetLabel?pageNum={currentPage}&pageSize={pageSize}&QryID={encodedCode}&QryName={encodedName}";
                HttpClientHelper helper = new HttpClientHelper();
                // 调用API
                string json = helper.RequestUrlNew(RequestType.Get, action, null);
                ApiPaging<List<LabelPrintModel>> model = JsonConvert.DeserializeObject<ApiPaging<List<LabelPrintModel>>>(json);
                // 使用安全的UI更新方式
                UpdateUIWithData(model);
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行查询时发生错误：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                // 确保分页控件可用
                if (paginationControl != null)
                {
                    paginationControl.Enabled = true;
                }
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 更新UI数据
        /// </summary>
        /// <param name="model">分页数据模型</param>
        private void UpdateUIWithData(ApiPaging<List<LabelPrintModel>> model)
        {
            if (model != null)
            {
                // 确保在UI线程上执行
                if (this.InvokeRequired)
                {
                    this.BeginInvoke(new Action(() => UpdateUIWithData(model)));
                    return;
                }

                // 更新数据源
                if (model.Data != null)
                {
                    // 假设有一个gridControl用于显示数据
                    gridControl1.DataSource = model.Data;
                }
                else
                {
                    gridControl1.DataSource = null;
                }

                // 更新分页控件
                if (paginationControl != null)
                {
                    totalCount = model.TotalCount;
                    paginationControl.TotalRecords = totalCount;
                    paginationControl.CurrentPage = currentPage;
                    paginationControl.PageSize = pageSize;
                    paginationControl.Enabled = true;
                    paginationControl.Refresh();
                }
            }
        }
        #endregion

        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
    }
}